package com.depin.pdaapp.utils;

import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.widget.ImageView;

import com.vondear.rxtool.view.RxToast;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by 哼哼
 * Date：2020/8/26 21:36
 * Desc:
 */
public class PicUtil {
    public static boolean SaveJpg(ImageView view) {

        try{
            Drawable drawable = view.getDrawable();
            if (drawable == null) {
                return false;
            }

            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");

            Uri dataUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            Uri fileUri = view.getContext().getContentResolver().insert(dataUri, values);

            // 如果保存不成功，insert没有任何错误信息，此时调用update会有错误信息提示
//            view.getContext().getContentResolver().update(dataUri, values, "", null);

            if(fileUri == null){

                return false;
            }

            OutputStream outStream = view.getContext().getContentResolver().openOutputStream(fileUri);

            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.flush();
            outStream.close();

            // 刷新相册
            /*
            String[] files = new String[1];
            String[] mimeTypes = new String[1];
            files[0] = filePath;
            mimeTypes[0] = "image/jpeg";
            MediaScannerConnection.scanFile(view.getContext(), files, mimeTypes, null);
            */
            view.getContext().sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", fileUri));
            RxToast.showToast("保存图片到相册完毕...");
            return true;

        }
        catch (IOException ex) {

        }
        return false;
    }
}